using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GGUIHorizontalLayout : MonoBehaviour
{
	public UIWidget container;

	public bool sorted = true;

	public bool hideInactive = true;

	private List<Transform> mChildren = new List<Transform>();

	public List<Transform> children
	{
		get
		{
			if (!Application.isPlaying)
			{
				mChildren.Clear();
			}
			if (mChildren.Count == 0)
			{
				Transform transform = base.transform;
				mChildren.Clear();
				for (int i = 0; i < transform.childCount; i++)
				{
					Transform child = transform.GetChild(i);
					if (!(child.GetComponent<UIWidget>() == null) && (bool)child && (bool)child.gameObject && (!hideInactive || NGUITools.GetActive(child.gameObject)))
					{
						mChildren.Add(child);
					}
				}
				if (sorted)
				{
					mChildren.Sort(SortByName);
				}
			}
			return mChildren;
		}
	}

	public static int SortByName(Transform a, Transform b)
	{
		return string.Compare(a.name, b.name);
	}

	private void Awake()
	{
		UICamera.onScreenResize = (UICamera.OnScreenResize)Delegate.Combine(UICamera.onScreenResize, new UICamera.OnScreenResize(OnScreenResize));
		NavigationManager.onLayerChanged += OnScreenResize;
	}

	private void OnDestroy()
	{
		UICamera.onScreenResize = (UICamera.OnScreenResize)Delegate.Remove(UICamera.onScreenResize, new UICamera.OnScreenResize(OnScreenResize));
		NavigationManager.onLayerChanged -= OnScreenResize;
	}

	private void OnEnable()
	{
		LayoutTimes(2);
	}

	private void OnScreenResize()
	{
		if (base.gameObject.activeInHierarchy)
		{
			LayoutTimes(2);
		}
	}

	private void LayoutTimes(int times)
	{
		StopAllCoroutines();
		StartCoroutine(DoLayoutTimes(times));
	}

	private IEnumerator DoLayoutTimes(int times)
	{
		for (int i = 0; i < times; i++)
		{
			Layout();
			yield return null;
		}
	}

	public void Layout()
	{
		if (!base.isActiveAndEnabled || children.Count == 0)
		{
			return;
		}
		Vector3[] localCorners = container.localCorners;
		int width = container.width;
		int width2 = width / children.Count;
		int num = 0;
		foreach (Transform child in children)
		{
			UIWidget component = child.GetComponent<UIWidget>();
			component.width = width2;
			Vector3 localPosition = component.cachedTransform.localPosition;
			localPosition.x = localCorners[0].x + (float)(component.width * num) + component.pivotOffset.x * (float)component.width;
			component.cachedTransform.localPosition = localPosition;
			num++;
		}
	}
}
